<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="16"
      :excludeValues="['taskArriveTime', 'beginTime']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
      @reset="() => (state.query.beginTime = null)"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <!-- <FIFormItem name="taskArriveTime" label="任务到达时间">
          <FIDatePicker v-model="state.query.taskArriveTime" type="daterange" start-placeholder="" end-placeholder="" />
        </FIFormItem> -->
        <FIFormItem class="date-range-class" name="taskArriveTime" label="任务到达时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.beginTime"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(date, state.query.endTime)"
          />
          <FIDatePicker
            v-model="state.query.endTime"
            value-format="YYYYMMDD"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(state.query.beginTime, date)"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processDefKey" label="流程名称">
          <ProcessName v-model="state.query.processDefKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="taskDefKey" label="任务名称">
          <TaskName v-model="state.query.taskDefKey" />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="taskStatus" label="任务状态">
          <FISelect
            v-model="state.query.taskStatus"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'open', label: '正运行' },
              { value: 'open_return', label: '回退运行' },
              { value: 'completed_return', label: '已完成' },
              { value: 'manual-finish', label: '回退完成' },
              { value: 'closed', label: '关闭' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="hasAuth" label="是否授权">
          <FISelect
            v-model="state.query.hasAuth"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'true', label: '是' },
              { value: 'false', label: '否' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="starter" label="流程发起人">
          <FISelect
            v-model="state.query.starter"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productNo" label="产品号">
          <FIInput v-model="state.query.productNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productName" label="产品名称">
          <FIInput v-model="state.query.productName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="prodPeriodNo" label="产品分期号">
          <FIInput v-model="state.query.prodPeriodNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="consignee" label="委托人">
          <FISelect
            v-model="state.query.consignee"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="sequenceId" label="流程实例号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="claimCond" label="任务领取状态">
          <FISelect
            v-model="state.query.claimCond"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: '1', label: '未领取与已领取' },
              { value: '2', label: '已被领取' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="completer" label="执行人">
          <FISelect
            v-model="state.query.completer"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="approveDeadline" label="完成截止时间">
          <FIDatePicker value-format="YYYYMMDD" v-model="state.query.approveDeadline" type="date" />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="startApp" label="发起系统">
          <FISelect
            v-model="state.query.startApp"
            :props="{ value: 'appCode', label: 'appName' }"
            :display-key="['appCode', 'appName']"
            :options="allStartAppArr"
            clearable
          >
            <!-- <template #option="{ scope }">
              <span>{{ scope.appCode }}</span
              ><span v-if="scope.appCode">&nbsp;-&nbsp;</span>
              <span>{{ scope.appName }}</span>
            </template> -->
          </FISelect>
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="id"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleActionClick"
    >
      <!-- 自定义列 moduleEname1 -->
      <!-- <template #manage="{ scope }">
        <FIButton
          v-if="
            scope.row.claimStatus == 'true' && (scope.row.taskStatus == 'open' || scope.row.taskStatus == 'open_return')
          "
          border
          size="small"
          @click="reassignConfirmSingle(scope)"
          >委托</FIButton
        >
        <FIButton border size="small">图形监控</FIButton>
      </template> -->

      <template #headerBtn>
        <FIPopconfirmBtn
          class="margin-left12"
          title="您是否确认批量委托选中数据吗？"
          beforePopText="请选择一条数据"
          buttonText="批量委托"
          :btn-binds="{ border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="bulkOperation()"
        />
        <FIButton id="export" class="margin-left12" :loading="exportLoading" type="primary" @click="exportClick"
          >导出</FIButton
        >
      </template>
    </FITable>
  </div>
  <FIModel
    v-model="reassignModelShow"
    title="选择委托人"
    width="620px"
    :confirmLoading="reassignForm.confirmLoading"
    @confirm="reassignConfirm"
  >
    <FIForm :model="reassignForm">
      <FIFormItem name="loginName" label="委托人">
        <!-- <FISelect
          v-model="reassignForm.loginName"
          valueCustom="loginName"
          :props="{ value: 'loginName', label: 'userCName' }"
          :options="allStarterArr"
          filterable
          @select="
            (item) => {
              reassignForm.userCName = item.userCName
            }
          "
        >
        </FISelect> -->
        <FISelect
          v-model="reassignForm.loginName"
          valueCustom="loginName"
          :props="{ value: 'loginName', label: 'userCName' }"
          :options="allStarterArr"
          :display-key="['loginName', 'userCName']"
          filterable
          @select="
            (item) => {
              reassignForm.userCName = item.userCName
            }
          "
        />
        <!-- <FIAutoInput
          v-model="reassignForm.userCName"
          :options="allStarterArr"
          value-key="userCName"
          :displayKey="['loginName', 'userCName']"
          placeholder="请输入"
          clearable
          @select="
            (item) => {
              reassignForm.loginName = item.loginName
            }
          "
        /> -->
      </FIFormItem>
    </FIForm>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import DeptTree from '../../components/DeptTree.vue'
import ProcessName from '../../components/ProcessName.vue'
import TaskName from '../../components/TaskName.vue'
import {
  apiQueryAllProcesses,
  apiQueryUser,
  apiQueryTask,
  apiQueryDept,
  apiQueryApp,
  apiReassignTasksBulk,
} from '@/api/modules/EWPT.js'
import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, checkDateDisabled, openUrlFn, useRouteNavigation } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
import LocalCache from '@/utils/cache'

// 路由对象
const route = useRoute()
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'pageMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const reassignModelShow = ref(false) // 委托弹窗显示

const state = reactive({
  // 查询条件
  query: {
    taskArriveTime: '', // 任务到达时间
    beginTime: null, // 任务到达开始时间'
    endTime: null, // 任务到达结束时间
    processDefKey: '', // 流程名称
    taskDefKey: '', // 任务名称
    taskStatus: '', // 任务状态
    hasAuth: '', // 是否有权限
    starter: '', // 流程发起人
    startDeptId: '', // 发起部门
    productNo: '', // 产品号
    productName: '', // 产品名称
    prodPeriodNo: '', // 产品分期号
    consignee: '', // 委托人
    sequenceId: '', // 流程实例号
    claimCond: '', // 任务领取状态 '':全部 1未领取与已领取，2:已被领取'
    completer: '', // 执行人
    approveDeadline: '', // 完成截止时间

    startApp: '', // 发起系统
    // ---------------分割线----------------------------------------------
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 批量委托表单数据
const reassignForm = ref({
  loginName: '',
  userCName: '',
  isBulk: false, // 是否为批量委托
  id: [],
  confirmLoading: false,
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '发起人',
    prop: 'starterName',
    align: 'center',
    width: '150',
  },
  {
    label: '状态',
    prop: 'taskStatusName',
    align: 'center',
    width: '120',
  },
  {
    label: '是否授权',
    prop: 'hasAuth',
    align: 'center',
    width: '100',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'false', label: '否' },
        { value: 'true', label: '是' },
      ],
    },
  },
  {
    label: '任务名',
    prop: 'name',
    align: 'center',
    width: '150',
  },
  {
    label: '产品号',
    prop: 'productNo',
    align: 'center',
    width: '150',
  },
  {
    label: '产品名称',
    prop: 'productName',
    align: 'center',
    width: '150',
  },
  {
    label: '项目号',
    prop: 'projectNo',
    align: 'center',
    width: '150',
  },
  {
    label: '项目名称',
    prop: 'projectName',
    align: 'center',
    width: '150',
  },
  {
    label: '合同号',
    prop: 'contractNo',
    align: 'center',
    width: '150',
  },
  {
    label: '合同名称',
    prop: 'contractName',
    align: 'center',
    width: '150',
  },
  {
    label: '执行者',
    prop: 'completerName',
    align: 'center',
    width: '120',
  },
  {
    label: '委托人',
    prop: 'consigneeName',
    align: 'center',
    width: '120',
  },
  // {
  //   label: '任务链接',
  //   prop: 'manage',
  //   align: 'center',
  //   width: '150',
  // },
  {
    label: '到达时间',
    prop: 'startTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '完成截止日期',
    prop: 'approveDeadline',
    align: 'center',
    minWidth: '160',
    editType: 'date-picker',
  },
  {
    label: '',
    prop: 'action',
    isCustomAction: true,
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}
watch(
  () => state.query.taskArriveTime,
  (newVal) => {
    if (!newVal) {
      state.query.beginTime = ''
      state.query.endTime = ''
    } else {
      if (newVal.length == 2) {
        state.query.beginTime = newVal[0]
        state.query.endTime = newVal[1]
      } else {
        state.query.beginTime = ''
        state.query.endTime = ''
      }
    }
  }
)

watch(
  () => reassignForm.value.userCName,
  (newVal) => {
    if (!newVal) {
      reassignForm.value.loginName = ''
    }
  }
)
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        Array.isArray(state.dataList) &&
          state.dataList.forEach((item: any) => {
            if (item.claimStatus == 'true' && (item.taskStatus == 'open' || item.taskStatus == 'open_return')) {
              item.dynamicActionConfig = [
                { id: 'reassign', type: '委托' },
                { id: 'trace', type: '图形监控' },
              ]
            } else {
              item.dynamicActionConfig = [{ id: 'trace', type: '图形监控' }]
            }
          })
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}

// 批量操作
const bulkOperation = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  reassignForm.value.id = []
  let cannotReassign = false
  for (const item of checkedRows.value) {
    const { taskStatus, claimStatus, id } = item
    if (claimStatus === 'claimed') {
      useMessage().warning('选取的任务包含被领取任务，无法委托！')
      cannotReassign = true
      break // 一旦发现不能重分配的情况，立即退出循环
    }

    if (['completed', 'completed_return', 'closed'].includes(taskStatus)) {
      useMessage().warning(`选择的任务包含${taskStatus === 'closed' ? '已关闭' : '已完成'}任务，无法委托！`)
      cannotReassign = true
      break // 一旦发现不能重分配的情况，立即退出循环
    }

    reassignForm.value.id.push(id)
  }
  if (cannotReassign) return
  // 批量委托
  reassignForm.value.isBulk = true
  reassignModelShow.value = true
}

const reassignConfirmSingle = (item) => {
  if (item.claimStatus != 'true' && item.taskStatus != 'open') {
    useMessage().warning('任务不在运行，无法委托')
    return
  }
  reassignForm.value.isBulk = false
  reassignModelShow.value = true
  reassignForm.value.id = [item.id]
}
// 单个委派、批量委托确认 如果传有id则为单个委托
const reassignConfirm = () => {
  if (!reassignForm.value.loginName) {
    useMessage().warning('请选择委托对象')
    return
  }
  let ids: string[] = []

  ids = reassignForm.value.id

  const tempUserCName = allStarterArr.value.find((item) => item.loginName === reassignForm.value.loginName)
  // reassignForm.value.userCName = tempUserCName.userCName
  const userData = LocalCache.getCache('user')
  let paramsObj = {
    operatorId: userData.loginName, //     委托操作用户ID operatorId
    operatorName: userData.userName, // 委托操作用户名称
    acceptorId: reassignForm.value.loginName, // 接收用户ID
    acceptorName: tempUserCName?.userCName, // 接收用户名称
    list: ids, // 委托任务ID列表 list
  }
  reassignForm.value.confirmLoading = true
  apiReassignTasksBulk(paramsObj)
    .then((res) => {
      reassignForm.value.confirmLoading = false
      if (res.data.success) {
        useMessage().success('委托成功')
        reassignModelShow.value = false
        if (reassignForm.value.isBulk) pageConfig.currentPage = 1
        searchFn()
      }
    })
    .catch(() => {
      reassignForm.value.confirmLoading = false
    })
}
const { navigateToPage } = useRouteNavigation()
// 操作按钮回调
const handleActionClick = (item, rowData, btnInfo) => {
  if (item.type == '委托') {
    reassignConfirmSingle(rowData)
  } else if (item.id == 'trace') {
    navigateToPage(item.id, rowData)
    // openUrlFn('trace', rowData)
  }
}

//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  const apiUrl = proxy.$Button_api('export', route.name)
  apiRequestExport(apiUrl, state.query)
    .then(() => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}

// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}

// 发起系统
const allStartAppArr = ref([])
// 查询发起系统
const getAllStartApp = () => {
  apiQueryApp().then((res) => {
    if (res.data.success === true) {
      allStartAppArr.value = res.data.data.result || []
    }
  })
}
onMounted(() => {
  getAllProcessesStarter()
  getAllStartApp()
  // 获取查询条件缓存
  const { cachedQuery } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  searchFn()
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
